//
//  OneViewController.m
//  cc
//
//  Created by ZLQ on 2016/10/24.
//  Copyright © 2016年 hbyj. All rights reserved.
//

#import "OneViewController.h"
#import "Masonry.h"
#import "FindCollectionViewCell.h"
#import "HomeWebViewController.h"
#import "UIImage+SYGenerateQrCode.h"
#import "SaoMaViewController.h"

#import "WXApi.h"
#import "WXApiObject.h"

#define HomeHeaderViewHeight 110
#define HomeRowItemCount 4

//#define KLINKSTR @"https://www.baidu.com/link?url=lV1hUtb7iigXGP4d0VcBTUTx4XLopvHysOIU3N3LJvBIWj7MuKzSyU14BAvCkeXgbhDwNpwBEpdUAXmnzeElWa&wd=&eqid=dab5812100009e37000000025731c53d"
#define iOS8 [[UIDevice currentDevice].systemVersion floatValue] >= 8.0
//#define ScreenWidth      [UIScreen mainScreen].bounds.size.width
#define RandomColor [UIColor colorWithRed:arc4random_uniform(256)/255.0 green:arc4random_uniform(256)/255.0 blue:arc4random_uniform(256)/255.0 alpha:1]

#define KLINKSTR @"https://www.baidu.com/"

#define DEFAULT 0


@interface OneViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>{
    NSTimer*_timer;
    NSInteger _count;
}
@property (nonatomic, weak) UIView *headerView;

@property (nonatomic, strong) NSArray *dataArray;

/**
 *  创建 UICollectionView
 */
@property (strong, nonatomic) IBOutlet UICollectionView *collectionView;
/**
 *  创建存放图片的数组
 */
@property(nonatomic,strong) NSMutableArray *imageNameArray;
/**
 *  创建存放标题的数组
 */
@property(nonatomic,strong) NSMutableArray *titleArray;
/**
 *  创建存放网址的数组
 */
@property(nonatomic,strong) NSMutableArray *urlArray;
@property(nonatomic,strong) UILongPressGestureRecognizer *longGR;

@property(nonatomic,strong) UIButton *button1;
@property(nonatomic,strong) UIButton *button2;

@property(nonatomic,strong) UIImageView *outImageView;

//生成二维码的文字
@property(nonatomic,strong) UITextField *textField;
@end

@implementation OneViewController
-(NSMutableArray *)urlArray{
    if (_urlArray == nil) {
        _urlArray = [NSMutableArray arrayWithObjects:
         @"http://www.365lgsc.com/",
         @"http://sjz.58.com/pets.shtml?utm_source=market&spm=b-31580022738699-me-f-824.bdpz_biaoti&PGTID=0d100000-000f-1e7f-5902-f6ed139ffff2&ClickID=1",
         @"https://2.taobao.com/",
         @"http://sjz.58.com/ershouche/?utm_source=market&spm=b-31580022738699-me-f-824.bdpz_biaoti&PGTID=0d100000-000f-1e7f-5902-f6ed139ffff2&ClickID=9",
         @"http://sjz.daojia.com/?hmsr=58_pc_shouye_home&utm_source=market&spm=b-31580022738699-me-f-824.bdpz_biaoti",
         @"http://sjz.58.com/job.shtml?utm_source=market&spm=b-31580022738699-me-f-824.bdpz_biaoti&PGTID=0d100000-000f-1e7f-5902-f6ed139ffff2&ClickID=7",
         @"http://sjz.58.com/ershoufang/?utm_source=market&spm=b-31580022738699-me-f-824.bdpz_biaoti&PGTID=0d100000-000f-1e7f-5902-f6ed139ffff2&ClickID=13",
         @"http://y.qq.com/",
         @"http://www.diyifanwen.com/tool/zhougongjiemeng/",
         @"http://image.baidu.com/search/index?tn=baiduimage&ct=201326592&lm=-1&cl=2&ie=gbk&word=%B1%DA%D6%BD%D7%C0%C3%E6&fr=ala&ala=1&pos=0&alatpl=wallpaper&oriquery=%E5%A3%81%E7%BA%B8%E6%A1%8C%E9%9D%A2#z=0&pn=&ic=0&st=-1&face=0&s=0&lm=-1",
         @"http://2016.cctv.com/medal_list/",
         @"http://www.365lgsc.com/", nil];
    }
    return _urlArray;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
    
    [self.collectionView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //self.view.backgroundColor = RGBColor(246, 246, 246);
    self.navigationItem.title = @"One";
    
    [self setupHeader];
    [self setupButtons];
}

- (void)setupHeader
{
    UIView *header = [[UIView alloc] init];
    header.frame = CGRectMake(0, 64, self.view.cc_width, HomeHeaderViewHeight);
    header.backgroundColor = [UIColor colorWithRed:(38 / 255.0) green:(42 / 255.0) blue:(59 / 255.0) alpha:1];
    [self.view addSubview:header];
    _headerView = header;
    
    UIButton *scan = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, header.cc_width * 0.5, header.cc_height)];
    [scan setImage:[UIImage imageNamed:@"home_scan_6"] forState:UIControlStateNormal];
    [scan addTarget:self action:@selector(scanButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [header addSubview:scan];
    
    UIButton *pay = [[UIButton alloc] initWithFrame:CGRectMake(scan.cc_width, 0, header.cc_width * 0.5, header.cc_height)];
    [pay setImage:[UIImage imageNamed:@"home_pay_6"] forState:UIControlStateNormal];
    [pay addTarget:self action:@selector(payButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [header addSubview:pay];
}

#pragma mark-> 布局
- (void)viewDidLayoutSubviews{
    /*
    __weak __typeof(self)weakSelf  = self;

    [_outImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(10);
        make.top.mas_equalTo(weakSelf.collectionView.mas_bottom).offset(-100);
        make.width.height.mas_equalTo(50);
    }];
     */
}

-(void)payButtonClicked{
    //NSLog(@"pay");
    
    NSString*link;
    if(self.textField.text.length==0){
        
        link=KLINKSTR;
        
    }else{
        
        link=self.textField.text;
    
    }
    UIImage *image = nil;
    
    switch (_count) {
        case 0:
            image = [UIImage generateImageWithQrCode:link QrCodeImageSize:0];
            break;
        case 1:
            image = [UIImage generateImageWithQrCode:link QrCodeImageSize:0 RGB:@"#ee68ba"];
            break;
        case 2:
            image = [UIImage generateImageWithQrCode:link QrCodeImageSize:0 insertImage:[UIImage imageNamed:@"backImage"] radius:16];
            break;
        case 3:
            image = [UIImage generateImageWithQrCode:link QrCodeImageSize:0 RGB:@"#ee68ba" insertImage:[UIImage imageNamed:@"backImage"] radius:16];
            break;
        case 4:
            image = [UIImage generateImageWithQrCode:link QrCodeImageSize:0 backgroundImage:[UIImage imageNamed:@"backImage"]];
            break;
        case 5:
            image = [UIImage generateImageWithQrCode:link QrCodeImageSize:0 RGB:@"#ee68ba" backgroundImage:[UIImage imageNamed:@"backImage"] insertImage:[UIImage imageNamed:@"backImage"] radius:16];
            break;
        case 6:
            image = [UIImage generateImageWithQrCode:link QrCodeImageSize:0 fillImage:[UIImage imageNamed:@"形状111"]];
            break;
        case 7:
            image = [UIImage generateImageWithQrCode:link QrCodeImageSize:0 fillImage:[UIImage imageNamed:@"形状222"] color1:@"#1dacea" color2:@"#2d9f7c"];
            break;
        case 8:
            image = [UIImage generateImageWithQrCode:link QrCodeImageSize:0 fillImage:[UIImage imageNamed:@"形状111"] color1:nil color2:nil backgroundImage:[UIImage imageNamed:@"backImage"]];
            break;
        case 9:
            image = [UIImage generateImageWithQrCode:link QrCodeImageSize:0 fillImage:[UIImage imageNamed:@"形状222"] color1:@"#d40606" color2:@"#a10acc" backgroundImage:[UIImage imageNamed:@"backImage"] insertImage:[UIImage imageNamed:@"backImage"] radius:16];
            break;
    }
    
    _count=(_count==9)?0:(_count+1);
    _outImageView.image=image;

}

-(void)setupButtons{
    UIScrollView *bottomView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_headerView.frame), WIDTH, HEIGHT-CGRectGetMaxY(_headerView.frame)-48)];
    bottomView.backgroundColor = RGBColor(246, 246, 246);
    [self.view addSubview:bottomView];

    {
        //初始化 UICollectionView
        UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
        flow.itemSize = CGSizeMake(WIDTH/4-8, WIDTH/4-8);
        // 距离 四周的距离 (上 左  下  右)
        flow.sectionInset = UIEdgeInsetsMake(0 , 0, 0, 0);
        //滑动方向
        //flow.scrollDirection = UICollectionViewScrollDirectionVertical;
        //flow.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        
        UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 10, WIDTH, WIDTH-20) collectionViewLayout:flow];
        self.collectionView = collectionView;
        collectionView.showsVerticalScrollIndicator = NO;
        
        collectionView.backgroundColor = RGBColor(246, 246, 246);
        
        [collectionView registerNib:[UINib nibWithNibName:@"FindCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:COLLECTION_CELL];
        
        #define ImageNameArray [NSArray arrayWithObjects:@"home_cz",@"home_dd",@"home_fl",@"home_jhs",@"home_qua",@"home_tjb",@"home_tmall",@"home_tmcs", nil]
        
        self.imageNameArray = [@[@"home_cz",@"home_dd",@"home_fl",@"home_jhs",@"home_qua",@"home_tjb",@"home_tmall",@"home_tmcs",@"home_tmcs",@"home_tmcs",@"home_tmcs",@"home_tmcs"]mutableCopy];
        self.titleArray = [@[@"河",@"北",@"盈",@"玖",@"电",@"子",@"商",@"务",@"有",@"限",@"公",@"司"]mutableCopy];
        
        collectionView.delegate = self;
        collectionView.dataSource = self;
        collectionView.backgroundColor = [UIColor clearColor];
        [bottomView addSubview:collectionView];
        

        
        _outImageView=[[UIImageView alloc]initWithFrame:CGRectMake(20, 330, 100, 100)];
        _outImageView.layer.borderWidth=2.0f;
        _outImageView.layer.borderColor=[UIColor redColor].CGColor;
        _outImageView.userInteractionEnabled=YES;
#ifdef DEFAULT
        /**普通默认黑色 */
        UIImage*tempImage = [UIImage generateImageWithQrCode:KLINKSTR QrCodeImageSize:0];;
        
#else
        /**彩色二维码 */
        
        UIImage*tempImage = [UIImage generateImageWithQrCode:KLINKSTR QrCodeImageSize:0 RGB:@"#ee68ba"];;
#endif
        
        
        _outImageView.image=tempImage;
//        _outImageView.image = [UIImage imageNamed:@"20000032Icon"];
        _outImageView.contentMode=UIViewContentModeScaleToFill;
        
        [bottomView addSubview:_outImageView];
        
        UITextField *field = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_outImageView.frame)+20, CGRectGetMinY(_outImageView.frame), 100, 30)];
        field.placeholder = @"请输入要生成的二维码内容";
        self.textField = field;
        [bottomView addSubview:field];
        
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMinX(field.frame), CGRectGetMaxY(field.frame)+20, 80, 30)];
        [button setTitle:@"微信支付" forState:normal];
        [button setTitleColor:[UIColor orangeColor] forState:normal];
        [button addTarget:self action:@selector(weixinPay) forControlEvents:UIControlEventTouchUpInside];
        [bottomView addSubview:button];
    }
}

-(void)weixinPay{
    //NSLog(@"~~~~");
    
    //============================================================
    // V3&V4支付流程实现
    // 注意:参数配置请查看服务器端Demo
    // 更新时间：2015年11月20日
    //============================================================
    NSString *urlString   = @"http://wxpay.weixin.qq.com/pub_v2/app/app_pay.php?plat=ios";
    //解析服务端返回json数据
    NSError *error;
    //加载一个NSURL对象
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    //将请求的url数据放到NSData对象中
    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if ( response != nil) {
        NSMutableDictionary *dict = NULL;
        //IOS5自带解析类NSJSONSerialization从response中解析出数据放到字典中
        dict = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
        
        NSLog(@"url:%@",urlString);
        if(dict != nil){
            NSMutableString *retcode = [dict objectForKey:@"retcode"];
            if (retcode.intValue == 0){
                NSMutableString *stamp  = [dict objectForKey:@"timestamp"];
                
                //调起微信支付
                PayReq* req             = [[PayReq alloc] init];
                req.partnerId           = [dict objectForKey:@"partnerid"];
                req.prepayId            = [dict objectForKey:@"prepayid"];
                req.nonceStr            = [dict objectForKey:@"noncestr"];
                req.timeStamp           = stamp.intValue;
                req.package             = [dict objectForKey:@"package"];
                req.sign                = [dict objectForKey:@"sign"];
                [WXApi sendReq:req];
                //日志输出
                NSLog(@"appid=%@\npartid=%@\nprepayid=%@\nnoncestr=%@\ntimestamp=%ld\npackage=%@\nsign=%@",[dict objectForKey:@"appid"],req.partnerId,req.prepayId,req.nonceStr,(long)req.timeStamp,req.package,req.sign );
}}}}

- (void)scanButtonClicked
{
    //SDBasicViewContoller *desVc = [[SDScanViewController alloc] init];
    //[self.navigationController pushViewController:desVc animated:YES];
    NSLog(@"扫一扫");
    
    SaoMaViewController *saoma = [[SaoMaViewController alloc] init];
    [self.navigationController pushViewController:saoma animated:YES];
}

#pragma mark --UICollectionView 代理方法

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.titleArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    FindCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:COLLECTION_CELL forIndexPath:indexPath];
    cell.backgroundColor = [UIColor clearColor];
    NSString *imageName = self.imageNameArray[indexPath.row];
    NSString *title = self.titleArray[indexPath.row];
    cell.logoImageView.image = [UIImage imageNamed:imageName];
    cell.titleLabel.text = title;
    
    //添加下划线
    NSMutableAttributedString *content = [[NSMutableAttributedString alloc] initWithString:cell.titleLabel.text];
    NSRange contentRange = {0, [content length]};
    [content addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:contentRange];
    cell.titleLabel.attributedText = content;
    
    //设置边框
    cell.layer.borderWidth = 1.f;
    cell.layer.borderColor = [UIColor grayColor].CGColor;
    //切圆角
    cell.layer.cornerRadius = cell.cc_width/2;
    
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(nonnull NSIndexPath *)indexPath{
    NSString *url = self.urlArray[indexPath.row];
    HomeWebViewController *web = [[HomeWebViewController alloc] initWithUrl:url];
    web.modelTitle = self.titleArray[indexPath.row];
    
    //[self.navigationController pushViewController:web animated:YES];
    
    UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:web];
    //navi.modalPresentationStyle = UIModalPresentationCurrentContext;
    [navi setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
    
    [self presentViewController:navi animated:YES completion:^{
        
    }];
}

//设置横向的行间距
- (CGFloat) collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 2.0f;
}

//设置纵向的行间距
- (CGFloat) collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 10.0f;
}

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row % 2 != 0) {
        cell.transform = CGAffineTransformTranslate(cell.transform, WIDTH/2, 0);
    }else{
        cell.transform = CGAffineTransformTranslate(cell.transform, -WIDTH/2, 0);
    }
    cell.alpha = 0.0;
    [UIView animateWithDuration:0.7 animations:^{
        cell.transform = CGAffineTransformIdentity;
        cell.alpha = 1.0;
    } completion:^(BOOL finished) {
        
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
